package com.starryx.driverschool.controller;

import com.starryx.driverschool.po.Teacher;
import com.starryx.driverschool.service.CarService;
import com.starryx.driverschool.service.TeacherService;
import com.starryx.driverschool.vo.TeacherQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private CarService carService;

    @GetMapping("/teacher")
    public String teacher(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                      Model model){
        model.addAttribute("page", teacherService.listTeacher(pageable));
        return "teacher";
    }

    @GetMapping("/teacher/input")
    public String input(Model model){
        model.addAttribute("teacher", new Teacher());
        model.addAttribute("cars", carService.listCarWithoutTeacher());
        return "teacher-input";
    }

    @GetMapping("/teacher/input/{id}")
    public String input(@PathVariable Long id, Model model){
        model.addAttribute("teacher", teacherService.getTeacher(id));
        model.addAttribute("cars", carService.listCarWithoutTeacher());
        return "teacher-input";
    }

    @PostMapping("/teacher/save")
    public String save(@Valid Teacher teacher,
                       BindingResult result,
                       RedirectAttributes attributes){
        Teacher teacher1 = teacherService.getTeacherByNo(teacher.getNo());
        if(teacher1 != null){
            result.rejectValue("no", "noError", "不能添加重复的教练信息");
        }
        if (result.hasErrors()){
            return "teacher-input";
        }
        teacher.setCar(teacher.getCar().getId() != null ? carService.getCar(teacher.getCar().getId()) : null);
        Teacher c = teacherService.saveTeacher(teacher);
        if(c == null){
            attributes.addFlashAttribute("message", "新增失败");
        }else{
            attributes.addFlashAttribute("message", "新增成功");
        }
        return "redirect:/teacher";
    }

    @PostMapping("/teacher/update")
    public String update(@Valid Teacher teacher,
                       BindingResult result,
                       RedirectAttributes attributes){
        Teacher teacher1 = teacherService.getTeacherByNo(teacher.getNo());
        if(teacher1 != null && !teacher1.getId().equals(teacher.getId())){
            result.rejectValue("no", "noError", "不能添加重复的教练信息");
        }
        if (result.hasErrors()){
            return "teacher-input";
        }
        teacher.setCar(teacher.getCar().getId() != null ? carService.getCar(teacher.getCar().getId()) : null);
        Teacher c = teacherService.updateTeacher(teacher.getId(), teacher);
        if(c == null){
            attributes.addFlashAttribute("message", "编辑失败");
        }else{
            attributes.addFlashAttribute("message", "编辑成功");
        }
        return "redirect:/teacher";
    }

    // 跳转到博客列表页面
    @PostMapping("/teacher/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         TeacherQuery teacherQuery,
                         Model model){
        model.addAttribute("page", teacherService.listTeacher(pageable, teacherQuery));
        return "teacher :: teacherList";       // 返回 blogList 片段，利用 thymeleaf 实现类似 ajax 那样的局部刷新
    }

    @GetMapping("/teacher/delete/{id}")
    public String delete(@PathVariable Long id, RedirectAttributes attributes){
        teacherService.deleteTeacher(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/teacher";
    }

    @PostMapping("/teacher/batchdelete")
    public String batchDelete(@RequestParam List<Long> ids, RedirectAttributes attributes){
        // 带有外键约束的表删到最后一项时会删不掉，所以要使用逻辑删除
        for(Long id : ids){
            teacherService.deleteTeacher(id);
        }
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/teacher";
    }
}
